var orderInfo;
var sampleTypeMap={
    '05':'干血片',
    '01':'全血',
    '08':'口腔拭子',
    '18':'唾液',
    '03':'DNA',
    '32':'其他'
}
function orderSheetOnLoad() {
    if($("#prdCode").val()){
        $("#prd-value").css('color', '#333')
        prdChange($("#prdCode").val());
    }
    if(orderData == null || orderData == undefined || orderData == '') return;
    orderInfo = JSON.parse(orderData);
    /* 根据status状态，进行不同处理,送检单状态：1未确认；  2 已确认，无法编辑 ; 0 默认值*/
    /* 0：空白页进行填写，1：有数据，进行编辑*/
    setValues();
}
function parseArea() {
    var area = $("#area-value").val();
    if (area == "") {
        // alert("请选择城市");
        return false;
    }
    var patten = /(\d{2})0000,(\d{4})00,(\d{6})|(\d{2})0000/g;
    var result = patten.exec(area);
    if (result != null) {
        if (result[4] == undefined) {
            $("#province").val(result[1]);
            $("#city").val(result[2]);
            $("#county").val(result[3]);
        }
        else {
            $("#province").val(result[4]);
            $("#city").val("");
            $("#county").val("");
        }
        return true;
    }
}

var tipTexts = {
    age : "出生日期不能晚于当前日期。",
    sampleNum:"请填写样本编号或点击'样本编号'扫码填入样本编号。",
    customer : "送检单位不能为空。",
    bloodDate : "采样日期不能为空。",
    gestationalWeekFigure : "性别不能为空。",
    birthday : "出生日期不能为空。",
    guardian : "请填写监护人姓名。",
    idType : "请填写证件类型。",
    phone : "手机号码填写有误，请在相应位置重新填写。",
    idnumber : "证件号码填写有误，请在相应位置重新填写。",
    sampleType:"请选择样本类型",
    sampleTypeOther:"请输入样本类型",
    address : "请填写详细地址。",
    province : "请完整填写现居地。",
    email : "请正确填写电子邮箱。",
    phonenone : "请在相应位置填写手机号码。",
    idnumbernone : "请在相应位置填写证件号码。",
    icephonenone : "请在相应位置输入紧急联系人的手机号码。",
    icephone : "号码填写有误，请在相应位置输入紧急联系人的手机号码。",
    name : "请在姓名位置填写受检者姓名。",
    location : "请在相应位置选择所在地。",
    prd : "请选择产品"
}


var iPhone = (navigator.userAgent.match(/iPhone/i));
var iPod = navigator.userAgent.match(/iPod/i);
var Android = navigator.userAgent.match(/Android/i);

var selectedTownId = "pd";

var totalPage = 0;
$(document).ready(function(){
    $('#coupon_icon').hide()
    initUrlInfo()
    queryCoupon()
    searchCustom();
});

//单选radio yes
function radioYes(id){
    $("#"+id+"-yes").attr("src","./images/order/radio-red.png");
    $("#"+id+"-no").attr("src","./images/order/radio-def.png");

    ///tips 提示
    $("#"+id+"-input").val(1);
}
//单选radio no
function radioNo(id){
    $("#"+id+"-yes").attr("src","./images/order/radio-def.png");
    $("#"+id+"-no").attr("src","./images/order/radio-blue.png");
    //$("#"+id+"-tips").css("height", "17px");
    $("#"+id+"-input").val(0);
}
//打开选择浮层
function openSelectTip(tipId){
    $("#fade").css('display','block');
    $("#"+tipId).css('display','block');

    $(function(){
        $("#fade").click(function(event){
            var id = event.target.id;
            if(id == 'fade'){ closeSelTips(tipId); }
        });

    });
}

//关闭遮罩层  关闭选择框   注销body click事件
function closeSelTips(tipId){
    selClose(tipId);
    selClose('fade');
    //解除绑定
    $("#fade").unbind('click');
}

function selClose(id){
    $("#"+id).css('display','none');
}

function selTown(obj){
    var id = obj.id;
    var value = $("#"+id).data("value") ;
    var input_value = $("#"+id).data("input");

    //填写地区code和地址信息
    $("#town-input").val(input_value);
    //$("#address-input").val("河南省新乡市长垣县"+value);

    if(id != selectedTownId){
        $("#"+id).addClass("selected");
        $("#"+selectedTownId).removeClass("selected");
        selectedTownId = id;
    }
    //alert(value);
    $("#town-value").text(value);
    $("#townp").css('color','#333');
    closeSelTips('changyuan');
}
//选择种族
function selrace(obj){
    var id = obj.id;
    var value = $("#"+id).data("value");
    var input_value = $("#"+id).data("input");
    $("#race-value").text(value);
    $("#race-value").css('color','#333');
    $("#race").val(input_value);
    //关闭浮层
    closeSelTips('raceSelDiv');
}
//选择单位
function selCustomer(obj){
    var id = obj.id;
    var value = $("#"+id).data("value");
    var input_value = $("#"+id).data("input");
    //alert(value);
    if(value.length > 15){
        value = value.substring(0,12) + '...';
    }
    $("#customer-value").text(value);
    $("#customer-value").css('color','#333');
    $("#customer").val(input_value);
    $("#customerName").val(value)
    //关闭浮层
    closeSelTips('customerSelDiv');

}
//选择性别
function selgestationalWeekFigure(obj){
    var id = obj.id;
    var value = $("#"+id).data("value") ;
    var input_value = $("#"+id).data("input");
    //alert(value);
    $("#gestationalWeekFigure-value").text(value);
    $("#gestationalWeekFigure-value").css('color','#333');
    $("#gestationalWeekFigure").val(input_value);
    //关闭浮层
    closeSelTips('gestationalWeekFigureSelDiv');

}
//选择产品
function selPrd(obj){
    var id = obj.id;
    var value = $("#"+id).data("value") ;
    var input_value = $("#"+id).data("input");
    //alert(value);
    $("#prd-value").text(value);
    $("#prd-value").css('color','#333');
    prdChange(input_value);
    $("#prdCode").val(input_value);
    //关闭浮层
    closeSelTips('prdSelDiv');
}
function selSampleType(obj){
    var id = obj.id;
    var value = $("#"+id).data("value");
    var input_value = $("#"+id).data("input");
    $("#sampleType-value").text(value);
    $("#sampleType-value").css('color','#333');
    $("#sampleType").val(input_value);
    if(input_value == '32'){
        $("#sampleType-line").show();
        $("#sampleTypeOtherDiv").show();
    }else{
        $("#sampleType-line").hide();
        $("#sampleTypeOtherDiv").hide();
        $("#sampleTypeOther").val('');
    }
    closeSelTips('sampleTypeSelDiv');
}
function prdChange(prdCode) {

    if(prdCode == 'DX1373'){
        $('#addressTitle').text('户籍地址');
        $('.gmclass').show();
    }else {
        $('#addressTitle').text('联系地址');
        $('.gmclass').hide();
    }
}
var selectedIdType = "NA";
function selIdType(obj, idSel) {
    var id = obj.id;
    var value = $("#"+id).data("value");
    var input = $("#"+id).data("input");
    if( id != selectedIdType)
    {
        $("#"+id).addClass("selected");
        $("#"+selectedIdType).removeClass("selected");
        selectedIdType = id;
        $("#idnumber").val('');
    }

    $("#idType-value").text(value);
    $("#idType-value").css('color', '#333');
    $("#idType").val(input);
    $("#idType-line").show();
    $("#idNumberDiv").show();
    closeSelTips(idSel);
}

function countAge(obj) {
    var birthDay = new Date($(obj).val());
    var today = new Date();

    if(birthDay > today){
        tipsMsg(tipTexts.age);
        return;
    }
    var birthYear = birthDay.getFullYear();
    var thisYear = today.getFullYear();
    var birthMonth = birthDay.getMonth();
    var thisMonth = today.getMonth();
    var ageY = parseInt(thisYear) - parseInt(birthYear);
    var ageM = parseInt(thisMonth) - parseInt(birthMonth);
    if(ageM < 0){
        ageY --;
        ageM += 12;
    }
    if(ageY<18){
        $('.childItem').show();
    }else{
        $('.childItem').hide();
        $('#guardian').val('');
    }
    var age = ageY + '岁';
    $("#age").val(age);
}
function familyDeafnessTips(){
    tipsMsg('“耳聋家族史：三代以内直系或旁系血亲出现听力损失，主要指受检者父母、兄弟姐妹、（外）祖父母及（外）祖父母兄弟姐妹。外力、交通事故、长期噪音工作环境等造成的听力损失不属于家族史。”')
}
function tipsMsg(msg){//打开提示框
    var tiptext = msg;
    if(!tiptext) return;
    openTips(tiptext);
}
function openTips(tiptext){
    //alert("tiptext:" + tiptext);
    $("#tipmsg").text(tiptext);
    $("#fade").css('display','block');
    //alert("show tipDia");
    $("#tipDia").css('display','block');
}
function closeTips(){//关闭提示框
    $("#tipDia").css('display','none');
    $("#fade").css('display','none');
}
//页面往上移动，防止键盘遮挡输入框
function upbody(){
    if(iPhone){
        //alert("is ios");
        return;
    }
    $("#ban_bt").css('margin-bottom','60%');
    window.scrollTo(0,document.body.scrollHeight);
}

function test(){
    alert("test msg--");
}
//检查表单提交
function checkForm(market){
    parseArea();
    var sampleInfos=[];
    var sampleType = $('#sampleType').val();
    var sampleTypeOther = $('#sampleTypeOther').val();
    var customer = $('#customer').val();
    var customerName = $('#customerName').val();

    var bloodDate = $('#bloodDate').val();
    var name = $.trim($("#name").val());
    var gestationalWeekFigure = $('#gestationalWeekFigure').val();
    
    var birthday = $('#birthday').val();
    var office = $('#office').val();
    var doctorName = $('#doctorName').val();
    var idType = 0;
    var idnumber = $('#idnumber').val();
    var province = $('#province').val();
    var city = $('#city').val();
    var county = $('#county').val();
    var address = $('#address').val();
    var areaOpt = $('#area-opt').val();
    var ethnic = $('#ethnic').val();
    var origin = $('#origin').val();
    var pregnancyInfection = $('#pregnancyInfection-input').val();
    var familyDeafness = $('#familyDeafness-input').val();
    var consanguineousMarriage = $('#consanguineousMarriage-input').val();
    var earDeformity = $('#earDeformity-input').val();
    var medicationHistory = $('#medicationHistory-input').val();
    var orderId = $('#orderId').val()
    if(!checkIdNumberNone('idnumber') || !checkIdNumber('idnumber'))
    {
        return false;
    }
    doSubmit();
}
var requiredKeys=["customerCode"];//必填项字段
function checkRequiredItems(params){//检查必填项
    for(var i in requiredKeys){
        if(!params[requiredKeys[i]]){
            openTips('请填写带星号的必填项');
            return false;
        }
    }
    return true;
}
var submiting = false;
function doSubmit(){
    if(submiting) return;
    submiting = true;
    var params={}; 
    var formInputs = $('input.submit').each(function(index,element){//遍历class为submit的input值
        var name = $(element).attr('name');
        var value = $(element).val();
        if(name && value){
            params[name] = value;
        }
    });
    var checkResult = checkRequiredItems(params);
    if(!checkResult){
        return;
    }
    params.sourceType='2';
    if(couponNum){
        params.couponNum = couponNum;
    }
    params.productName = '产前血清学筛查';
    params.productCode = 'BS0001';

    //设置模板文件，pc端送检单列表点击编辑才可以进入编辑界面
    params.fileVer = "temp/sample1.jsp";
    
     // alert(JSON.stringify(params));
    $("#bindbtn").attr("disabled","true");//点击提交禁止再次点击
    $.ajax({
        type:"post",
        async:false,
        url:"/csfy/wx/createSampleBase.do",
        data:params,
        dataType:"json",
        success:function (data) {
            openTips('提交成功');
            $('body').html('<div style="margin-top:100px;text-align:center;color:#00ff00;font-size:30px;">送检单提交成功</div>');
            submiting = false;
        },
        error:function(data){
            alert('出错了!');
            submiting = false;
        }
    });
}

function checkAge() {

}
function checkMobile(mobile){

    var m=$.trim($("#"+mobile).val());
    if((/^16\d{9}$/.test( m ))| (/^13\d{9}$/.test( m )) | (/^15\d{9}$/.test( m ) ) | (/^18\d{9}$/.test( m ))  | (/^17\d{9}$/.test( m )) | (/^14\d{9}$/.test( m )) |(/^19\d{9}$/.test( m ))){
        return true;
    }
    tipsMsg(tipTexts[mobile]);
    return false;
}

function checkMobileNone(mobile)
{
    var m=$.trim($("#"+mobile).val());
    if(m.length == 0)
    {
        tipsMsg(tipTexts[mobile + 'none']);
        return false;
    }

    return true;
}

function checkIdNumberNone(idnumber)
{
    var text = $.trim($("#"+idnumber).val());
    if(text.length == 0)
    {
        tipsMsg(tipTexts.idnumbernone);
        return false;
    }
    return true;
}


var regIdCard=/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;

function checkIdNumber(idnumber)
{
    var text = $.trim($("#"+idnumber).val());
    if(!regIdCard.test(text))
    {
        //alert("length " + text.length);
        tipsMsg(tipTexts.idnumber);
        return false;
    }
    return true;
}


function checkNumber(num ,min,max){
    var n=$.trim($("#"+num).val());
    if( /^[1-9](\d+)?$/.test( n ) ){
        if(n>min && n<max)return true;
    }
    return false;
}

function triggerDate()
{
    $("#lastPeriod").trigger('click');
}

function triggerArea()
{
    $("#area-opt").trigger('click');
    $("#area-opt").blur();
}

function genAreaText(province, city, county) {
    if(province == "") return "";
    var areaText = "";
    var provinceText = province+"0000";
    var cityText = city+"00";
    var countyText = county + "";
    $.each(provs_data,function () {
        if(this.value == provinceText)
        {
            areaText+=this.text;
            return false
        }
    });

    $.each(citys_data[provinceText],function () {
        if(this.value == cityText)
        {
            areaText+=",";
            areaText+=this.text;
            return false
        }
    });

    $.each(dists_data[cityText],function () {
        if(this.value == countyText)
        {
            areaText+=",";
            areaText+=this.text;
            return false
        }
    });

    return areaText;
}

function genAreaValue(province, city, county) {
    var areaValue = "";
    if(province != "") areaValue+=province;
    if(city != "")
    {
        areaValue+=",";
        areaValue+=city;
    }
    if(county != "")
    {
        areaValue+=",";
        areaValue+=county;
    }
    return areaValue;
}
function queryCity(customerCode) {
    var cityName = "";
    var jsonObj = JSON.parse(hospitalData);
    // console.log(jsonObj);
    $.each(jsonObj,function () {
        if(this.code === customerCode)
        {
            var cityCode = this.city+"00";
            var proviceCode = this.province+"0000";
            $.each(citys_data[proviceCode],function () {
                if(this.value == cityCode)
                {
                    cityName = this.text;
                    return;
                }
            });
            return;
        }
    });
    return cityName;
}
function setIdType(idType) {
    var typeText = "";
    if(idType == 0) typeText = "身份证";
    if(idType == 1) typeText = "护照";
    $("#idType-value").text(typeText);
    $("#idType-value").css("color", "#333");
    $("#idtype-"+idType).addClass("selected");
    $("#idType-line").show();
    $("#idNumberDiv").show();
}
function setSampleType(input_value,sampleTypeOther){
    var sampleType = sampleTypeMap[input_value];
    $("#sampleType-value").text(sampleType);
    $("#sampleType-value").css('color','#333');
    $("#sampleType").val(input_value);
    if(input_value == '32'){
        $("#sampleType-line").show();
        $("#sampleTypeOtherDiv").show();
    }else{
        $("#sampleType-line").hide();
        $("#sampleTypeOtherDiv").hide();
        $("#sampleTypeOther").val(sampleTypeOther);
    }
}
function setRadio(value,id) {
    if(value==1){
        radioYes(id);
        return;
    }
    if(value==0){
        radioNo(id);
        return;
    }
}
function setValues()
{
    var customerName = orderInfo.customerName
    if (customerName) {
        if(customerName.length > 15){
            customerName = customerName.substring(0,12) + '...';
        }
        $("#customer-value").text(customerName);
        $("#customer-value").css('color','#333');
    }
    if (orderInfo.sampleInfos) {
        var sampleInfo = orderInfo.sampleInfos[0]
        $("#prdCode").val(sampleInfo.productCode);
        prdChange(sampleInfo.productCode);
        $("#prd-value").text(sampleInfo.productName)
        $("#prd-value").css('color', '#333')
    }
    var sex = ''
    if(orderInfo.sampleSex==1){
        sex='男'
    }else{
        sex='女'
    }
    $("#gestationalWeekFigure-value").text(sex);
    $("#gestationalWeekFigure-value").css('color','#333');
    setSampleType(orderInfo.sampleType,orderInfo.sampleTypeOther);
    setRadio(orderInfo.familyDeafness,'familyDeafness');
    setRadio(orderInfo.pregnancyInfection,'pregnancyInfection');
    setRadio(orderInfo.consanguineousMarriage,'consanguineousMarriage');
    setRadio(orderInfo.earDeformity,'earDeformity');
    setRadio(orderInfo.medicationHistory,'medicationHistory');
    // setIdType(orderInfo.idCardType);
    $("#area-opt").val(genAreaText(orderInfo.addressProvince, orderInfo.addressCity, orderInfo.addressCounty));
    $("#area-value").val(genAreaValue(orderInfo.addressProvince, orderInfo.addressCity, orderInfo.addressCounty));
}
function useCoupon(){
    openSelectTip('couponSelDiv')
    queryCoupon()
}
//选择优惠券
function selCoupon(obj){
    var id = obj.id;
    var value = $("#"+id).data("value") ;
    var status = $("#"+id).data("status");
    var productCode = $('#'+id).data("code");
    var idCard = $("#"+id).data("idCard");
    $('#idnumber').val(idCard);
    if(status != 1) return;
    if(productCode!='BS0001') return;
    setIdType(0)
    var input_value = $("#"+id).data("input");
    couponNum=input_value
    hasCoupon(true)
    //关闭浮层
    closeSelTips('couponSelDiv');

}

function hasCoupon(flag){
    if(flag===true){
        $('#coupon_title').text('已使用免费券')
        $('#coupon_icon').show()
        $('#idnumber').val(personInfo.id)
        $('#name').val(personInfo.name)
        
    }else{
        $('#coupon_title').text('点击使用免费券')
        $('#coupon_icon').hide()
    }
    
}
//搜索优惠券
function queryCoupon(){
    doQueryCoupon();
    var rows=[{type:1,couponNum:'11B2232','couponName':'长沙市民生项目NIPT免费券',couponDesc:'',barcodeImg:'',idCard:'4301081984022311',status:0},{type:1,couponNum:'11B2232','couponName':'长沙市民生项目NIPT免费券',couponDesc:'',barcodeImg:'',idCard:'4301081984022311',status:0},{type:1,couponNum:'11B2232','couponName':'长沙市民生项目NIPT免费券',couponDesc:'',barcodeImg:'',idCard:'4301081984022311',status:0},]
    var cusStr = '';
}
var personInfo={}
function doQueryCoupon(){//加载优惠券
    $.ajax({
        type:"post",
        url:"/csfy/user/getPresonInfo.do",
        data:{},
        dataType:"json",
        success:function (data) {
            if(data.code == 200){
                var info = data.data || {};
                personInfo.id=info.id;
                personInfo.name=info.name;
                var rows = info.couponInfos;
                var cusStr = '';
                if(rows) {
                    for(var key in rows){
                        var obj = rows[key];
                        obj.idCard=personInfo.id;
                        // if(obj.type===2) continue;
                        var couponStatus = obj.status;
                        var statusTip = '已审核(可用)';
                        var liStatus = couponStatus==1?1:0;
                        if(obj.productCode!='BS0001') {
                            statusTip = '已审核';
                            liStatus=0;
                        }
                        if(couponStatus==0){
                            statusTip = '未审核';
                        }else if(couponStatus==-1){
                            statusTip = '审核不通过';
                        }else if(couponStatus==2){
                            statusTip = '已使用';
                        }

                        var str = '<li style="height:auto;" id="coupon-'+key+'" data-idCard="'+obj.id+'" data-code="'+obj.productCode+'" data-input="'+obj.couponNum+'" data-status="'+obj.status+'" data-value="'+obj.couponName+'" class="sel-info coupon_sel_'+liStatus+'" onclick="selCoupon(this);"><div class="coupon_sel_info"><div class="coupon_sel_name">'+obj.couponName+'</div><div class="coupon_sel_tip">限身份证号码为'+obj.id+'使用--'+statusTip+'</div></div><div class="coupon_sel_iconbox"><div class="coupon_sel_status_'+couponStatus+'" ></div></div><div style="clear: both; height:60px;width:240px;"><img style="display:block;width:100%;height:100%;" src="'+obj.couponImg+'"></div></li><li><div class="input-line"></div></li>';
                        cusStr += str;
                    }
                    $('#couponBox').html(cusStr);
                } else {
                    var str = '<li style="text-align:center;color: #00afee;" id="coupon-'+ 0 +'" data-input="'+''+'" data-value="'+''+'" class="sel-info" onclick="selCoupon(this);">'+'您还没有免费券,您可以在公众号点击菜单我的服务-->领取免费券'+'</li><div class="input-line"></div>';
                    $('#couponBox').html(str);
                }
            }else {
                alert(data.msg);
            }

        }
    });
}

function gttWeekChange(tag){
    var week = $('#gttWeek-'+tag).val()||0;
    var day = $('#gttDay-'+tag).val()||0;
    $('#'+tag+'GestationalWeek').val(week+'+'+day);
}
function gttDayChange(tag){
    var week = $('#gttWeek-'+tag).val()||0;
    var day = $('#gttDay-'+tag).val()||0;
    $('#'+tag+'GestationalWeek').val(week+'+'+day);
}
function initUrlInfo(){
	var url = location.search;
	url = decodeURI(url);
	url = decodeURI(url);
	var Request = new Object();
	if(url.indexOf("?")!=-1){
	    var str = url.substr(1);//去掉?号
	    strs = str.split("&");
	    for(var i=0;i<strs.length;i++){
	    	var key = strs[i].split("=")[0];
	    	var value = unescape(strs[i].split("=")[1]);
	        Request[key]=value;
	        var keyId = '#' + key;
	        $(keyId).text(value);
	    }
	}
    couponNum = Request['couponNum']||'';
    if(couponNum){
        hasCoupon(true)
    }else{
        hasCoupon(false)
    }
}